package com.food.platformmsgmanagement.adapter.outbound;

import com.food.platformmsgmanagement.adapter.inbound.AlimentDTO;
import com.food.platformmsgmanagement.adapter.inbound.CommentDTO;
import com.food.platformmsgmanagement.domain.Aliment;
import com.food.platformmsgmanagement.domain.Comment;
import com.food.platformmsgmanagement.domain.Status;
import com.food.platformmsgmanagement.port.outbound.AlimentRepository;
import org.springframework.data.jdbc.repository.query.Modifying;
import org.springframework.data.jdbc.repository.query.Query;
import org.springframework.data.repository.CrudRepository;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * TODO 评论好像涉及到多表查询，还没写
 * spring data jdbc不支持直接通过方法名获得基本的查询功能，而是必须通过在 @Query 中定义 SQL 实现
 * 所以要写一下
 * @author 24270
 */
@Transactional
public interface AlimentJdbcRepository extends AlimentRepository, CrudRepository<Aliment, String> {

    @Override
    @Query("select * from aliment")
    List<AlimentDTO> queryAllAliment();

    @Override
    @Query("select * from aliment where id = :id")
    AlimentDTO queryOneAliment(String id);

    @Override
    default String addAliment(Aliment aliment) {
        System.out.println(aliment.id());
        insertAliment(aliment.id(), aliment.title(), aliment.mainText(), aliment.imgList().toString(), aliment.status().name());
        return aliment.id();
    }

    @Modifying
    @Query("INSERT INTO aliment VALUES (:id, :title, :mainText, :imgList, :status)")
    void insertAliment(String id, String title, String mainText, String imgList, String status);

    @Override
    @Modifying
    @Query("UPDATE aliment SET status = :status WHERE id = :id")
    void updateAlimentState(String id, String status);

    @Override
    @Modifying
    @Query("UPDATE aliment SET imgList = :imgList WHERE id = :id")
    void updateAlimentImg(String imgList, String id);

    @Override
    @Modifying
    @Query("DELETE FROM aliment WHERE id = :id")
    boolean deleteAliment(String id);

    @Override
    @Query("select * from comment WHERE alimentId = :alimentId")
    List<CommentDTO> queryAllComment(String alimentId);

    @Override
    @Query("select * FROM comment ORDER BY id DESC LIMIT 0,:number")
    List<CommentDTO> queryNumComment(String alimentId, int number);

    @Override
    default void addComment(Comment comment) {
        insertComment(comment.getId().value(), comment.getAlimentId(), comment.getUserName(), comment.getMainText().value(), comment.getDate());
    }

    @Modifying
    @Query("INSERT INTO comment VALUES (:id, :alimentId, :userName, :mainText, :date)")
    void insertComment(String id, String alimentId, String userName, String mainText, Date date);

    @Override
    @Modifying
    @Query("DELETE FROM comment WHERE id = :id")
    boolean deleteComment(String id);
}
